<script lang="ts" setup>
import {
  ElButton,
  ElInput,
  ElTable,
  ElSwitch,
  ElPagination,
  ElSelect,
  ElOption,
  ElMessageBox,
  ElMessage,
  ElRow,
  ElCol,
  ElImage,
  ElTabs,
  ElTabPane,
  ElPopover,
  ElProgress,
  ElTooltip,
} from "element-plus";
// import { Plus, Back } from "@vben/icons";
import { onMounted, ref, watch, computed, nextTick } from "vue";
import { router } from "#/router";
import {
  getDirectory,
  deleteMedia,
  deleteMore,
  batchDownload,
  directoryDownload,
} from "#/api/sys/media";
import { useDebounceFn } from "@vueuse/core";
import share from "./share.vue";
import type { EchartsUIType } from "@vben/plugins/echarts";
import { EchartsUI, useEcharts } from "@vben/plugins/echarts";

const activeName = ref("first");
const title = ref(router.currentRoute.value.query.name);
const name = ref("");
const status = ref("");
// 定义 localStorage 的 key
const STORAGE_KEY = "media_selected_items";
// 添加一个响应式变量来跟踪选中项数量
const selectedCount = ref(0);
const tableData = ref([
  // {
  //   id: 2,
  //   url: "/static/tip.png",
  //   name: "截图",
  //   size: "123KB",
  //   type: "JPG图片文件",
  //   createTime: "2022-01-02 09:00:00",
  // },
  // {
  //   id: 3,
  //   url: "/static/audio.png",
  //   name: "音频.jpg",
  //   size: "123KB",
  //   type: "音频文件",
  //   createTime: "2022-01-02 09:00:00",
  // },
  // {
  //   id: 4,
  //   url: "https://s.ibaotu.com/video/shipin.mp4",
  //   name: "高空监控视频.wav",
  //   size: "123KB",
  //   type: "wav文件",
  //   createTime: "2022-01-02 09:00:00",
  // },
  // {
  //   id: 1,
  //   url: "/static/file.png",
  //   name: "test1",
  //   size: "123KB",
  //   type: "文件夹",
  //   createTime: "2022-01-02 09:00:00",
  // },
]);
const defaultUrl = ref("/static/file.png");
let currentPage = ref(1);
let pageSize = ref(10);
let total = ref(0);
const multipleTableRef = ref();
const multipleSelection = ref([]);
const ids = ref([]);
// 饼图
const chartRef = ref<EchartsUIType>();
const { renderEcharts } = useEcharts(chartRef);

// 数据
const chartData = ref([
  { name: "照片", value: 20, itemStyle: { color: "#FACC14" } },
  { name: "视频", value: 40, itemStyle: { color: "#1890FF" } },
  { name: "音频", value: 40, itemStyle: { color: "#30C465" } },
]);

const totalSize = ref("220MB");
let chartInstance = ref(null);

const getSelectedIdsFromStorage = () => {
  try {
    const stored = localStorage.getItem(STORAGE_KEY);
    return stored ? JSON.parse(stored) : [];
  } catch (e) {
    console.error("解析存储的选择项失败:", e);
    return [];
  }
};

const saveSelectedIdsToStorage = (ids: number[]) => {
  try {
    localStorage.setItem(STORAGE_KEY, JSON.stringify(ids));
  } catch (e) {
    console.error("保存选择项到存储失败:", e);
  }
};

const clearSelectedIdsStorage = () => {
  localStorage.removeItem(STORAGE_KEY);
};

const isDownloading = ref(false);
const isDeleting = ref(false);
const batchButtonState = computed(() => {
  // 添加删除状态的判断，确保在删除过程中按钮也是禁用的
  const isProcessing = isDownloading.value || isDeleting.value;

  return {
    type: selectedCount.value >= 2 && !isProcessing ? "primary" : "info",
    disabled: selectedCount.value < 2 || isProcessing,
  };
});

// 监听localStorage变化，确保按钮状态更新
const updateBatchButtonState = () => {
  // 触发batchButtonState重新计算
  return batchButtonState.value;
};

watch([title, totalSize], () => {
  initChart();
});

const initChart = () => {
  if (!chartRef.value) return;

  renderEcharts({
    tooltip: {
      trigger: "item",
      formatter: "{b}: {c} ({d}%)",
    },
    legend: {
      show: false,
    },
    series: [
      {
        type: "pie",
        radius: ["40%", "70%"],
        center: ["50%", "50%"],
        avoidLabelOverlap: false,
        label: {
          show: true,
          position: "outside",
          formatter: "{b}: {d}%",
          fontSize: 12,
          color: "#303133",
          lineHeight: 16,
          padding: [0, 0, 0, 10],
        },
        labelLine: {
          show: true,
          length: 10,
          length2: 10,
          smooth: true,
        },
        data: chartData.value,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: "rgba(0, 0, 0, 0.5)",
          },
        },
      },
    ],
    title: {
      text: title.value || "媒体数据",
      subtext: totalSize.value,
      top: "35%",
      left: "48%",
      textAlign: "center",
      textStyle: {
        fontSize: 12,
        fontWeight: "normal",
        color: "gray",
        width: 50,
        overflow: "truncate",
        ellipsis: "...",
      },
      subtextStyle: {
        fontSize: 13,
        fontWeight: "bold",
        color: "#303133",
      },
      // 当鼠标悬停在标题上时显示完整文本
      triggerEvent: true,
    },
  });
};

const handleBack = () => {
  clearSelectedIdsStorage();
  router.go(-1);
};

const spaceInput = (value: string) => {
  // 过滤空格
  name.value = value.replace(/\s+/g, "");
};

const handleSelectionChange = (val: any[]) => {
  multipleSelection.value = val;
  const currentPageIds = tableData.value.map((item) => item.id);
  let storedIds = getSelectedIdsFromStorage();

  // 从存储中移除当前页的 ID(避免重复)
  storedIds = storedIds.filter((id: number) => !currentPageIds.includes(id));

  // 添加当前页选中的 ID
  const currentPageSelectedIds = val.map((item) => item.id);
  const newStoredIds = [...storedIds, ...currentPageSelectedIds];

  // 保存到 localStorage
  saveSelectedIdsToStorage(newStoredIds);

  // 更新 IDs 列表
  ids.value = newStoredIds;

  // 更新选中项计数
  selectedCount.value = newStoredIds.length;
};

// 记录当前文件夹ID,用于检测目录切换
const currentFolderId = ref<string | number>("");
// 记录当前设备ID,用于检测设备切换
const currentDeviceId = ref<string | number>("");

const search = async () => {
  const params = {
    fileName: name.value,
    currentPage: currentPage.value,
    pageSize: pageSize.value,
    deviceId: router.currentRoute.value.query.deviceId,
    deviceType: router.currentRoute.value.query.deviceType,
    parentId: router.currentRoute.value.query.parentId,
  };

  const { data } = await getDirectory(params);

  if (data.records.length > 0) {
    data.records.forEach((item) => {
      if (item.fileType == 1) {
        item.suffix = "文件夹";
      }
    });
    tableData.value = data.records;
    total.value = data.total;

    // 检测是否切换了设备
    const newDeviceId = router.currentRoute.value.query.deviceId || "";
    const hasDeviceChanged =
      currentDeviceId.value !== "" && currentDeviceId.value !== newDeviceId;

    // 如果切换了设备,清除所有选中项
    if (hasDeviceChanged) {
      clearAllSelection();
    }

    // 更新当前设备ID
    currentDeviceId.value = newDeviceId;

    // 检测是否切换了目录
    const newFolderId = router.currentRoute.value.query.parentId || "0";
    const hasFolderChanged =
      currentFolderId.value !== "" && currentFolderId.value !== newFolderId;

    // 如果切换了目录(进入或返回),清除所有选中项
    if (hasFolderChanged) {
      clearAllSelection();
    }

    // 更新当前文件夹ID
    currentFolderId.value = newFolderId;

    const storedIds = getSelectedIdsFromStorage();
    selectedCount.value = storedIds.length;

    // 计算当前页应该选中的项
    const currentPageSelected = tableData.value.filter((row) =>
      storedIds.includes(row.id)
    );

    // 先更新 multipleSelection，避免在 DOM 更新过程中触发不必要的事件
    multipleSelection.value = currentPageSelected;

    // 在 DOM 更新后恢复选中状态
    nextTick(() => {
      // 遍历当前页数据，恢复选中状态
      tableData.value.forEach((row) => {
        if (storedIds.includes(row.id)) {
          multipleTableRef.value?.toggleRowSelection(row, true);
        } else {
          // 确保未选中的项正确取消选中
          multipleTableRef.value?.toggleRowSelection(row, false);
        }
      });
    });
  } else {
    tableData.value = [];
    total.value = 0;
    multipleSelection.value = [];
    selectedCount.value = 0;
  }
};

const clearAllSelection = () => {
  multipleSelection.value = [];
  ids.value = [];
  selectedCount.value = 0;
  multipleTableRef.value?.clearSelection();
  clearSelectedIdsStorage();
};

const debouncedSearch = useDebounceFn(search, 500);

const resetForm = () => {
  name.value = "";
  status.value = "";
  currentPage.value = 1;
  clearAllSelection();
  search();

  // 触发按钮状态更新
  setTimeout(() => {
    updateBatchButtonState();
  }, 0);
};
const handleSizeChange = (val) => {
  pageSize.value = val;
  search();
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
  search();

  // 触发按钮状态更新
  setTimeout(() => {
    updateBatchButtonState();
  }, 0);
};

const shareModal = ref();
const shareItem = (row) => {
  shareModal.value.openDialog(row);
};

const moreShare = () => {
  const storedIds = getSelectedIdsFromStorage();
  if (storedIds.length === 0) {
    ElMessage({
      message: "请选择要分享的文件",
      type: "warning",
    });
  } else {
    shareModal.value.openDialog(storedIds);
  }
};

const downloadItem = async (row) => {
  // 判断是否为文件夹
  if (row.fileType == "1") {
    try {
      const { data } = await directoryDownload({ id: row.id });

      // 从URL中提取文件名
      let filename = "download.zip"; // 默认文件名

      if (data) {
        try {
          // 使用正则表达式从URL中提取文件名
          const urlParts = data.split("/");
          const fileNameWithParams = urlParts[urlParts.length - 1]; // 获取最后一部分
          const fileName = fileNameWithParams.split("?")[0]; // 去掉参数部分

          if (fileName) {
            filename = fileName;
          }
        } catch (parseError) {
          console.warn("解析文件名失败，使用默认文件名:", parseError);
        }

        // 创建一个隐藏的<a>元素来触发下载
        const link = document.createElement("a");
        link.href = data;
        link.setAttribute("download", filename);
        link.style.display = "none";

        // 添加到DOM中并触发点击
        document.body.appendChild(link);
        link.click();

        // 清理
        document.body.removeChild(link);

        clearAllSelection();
      } else {
        ElMessage.error("下载链接无效");
      }
    } catch (error) {
      ElMessage.error("批量下载失败: " + (error.message || "未知错误"));
      console.error("批量下载失败:", error);
    }
  } else {
    // 图片直接下载
    try {
      if (!row.fileUrl) {
        ElMessage.warning("文件地址无效");
        return;
      }

      // 获取文件数据
      const response = await fetch(row.fileUrl);

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }

      // 转换为blob
      const blob = await response.blob();

      // 创建对象URL
      const url = window.URL.createObjectURL(blob);
      const link = document.createElement("a");
      link.href = url;

      // 设置下载文件名
      let filename = row.fileName || "download";
      if (row.suffix) {
        filename = `${filename}.${row.suffix}`;
      }

      link.setAttribute("download", filename);
      link.style.display = "none";

      // 添加到DOM中并触发点击
      document.body.appendChild(link);
      link.click();

      // 清理
      document.body.removeChild(link);
      window.URL.revokeObjectURL(url);
    } catch (error) {
      // 如果直接下载失败，降级到新窗口打开
      ElMessage.warning("直接下载失败，将在新窗口打开文件");
      window.open(row.fileUrl, "_blank");
    }
  }
};

const moreDownload = async () => {
  const storedIds = getSelectedIdsFromStorage();

  if (storedIds.length === 0) {
    ElMessage({
      message: "请选择要下载的文件",
      type: "warning",
    });
    return;
  }

  // 设置下载状态为正在进行
  isDownloading.value = true;

  try {
    const { data } = await batchDownload({ ids: storedIds });

    // 从URL中提取文件名
    let filename = "download.zip"; // 默认文件名

    if (data) {
      try {
        // 使用正则表达式从URL中提取文件名
        const urlParts = data.split("/");
        const fileNameWithParams = urlParts[urlParts.length - 1]; // 获取最后一部分
        const fileName = fileNameWithParams.split("?")[0]; // 去掉参数部分

        if (fileName) {
          filename = fileName;
        }
      } catch (parseError) {
        console.warn("解析文件名失败，使用默认文件名:", parseError);
      }

      // 创建一个隐藏的<a>元素来触发下载
      const link = document.createElement("a");
      link.href = data;
      link.setAttribute("download", filename);
      link.style.display = "none";

      // 添加到DOM中并触发点击
      document.body.appendChild(link);
      link.click();

      // 清理
      document.body.removeChild(link);

      // 下载成功后清除选中项
      clearAllSelection();

      // 显示成功消息
      ElMessage.success("批量下载成功");
    } else {
      ElMessage.error("下载链接无效");
    }
  } catch (error) {
    ElMessage.error("批量下载失败: " + (error.message || "未知错误"));
    console.error("批量下载失败:", error);
  } finally {
    // 无论成功还是失败，都要重置下载状态
    isDownloading.value = false;
  }
};

const moreDelete = async () => {
  const storedIds = getSelectedIdsFromStorage();

  if (storedIds.length === 0) {
    ElMessage({
      message: "请选择要删除的文件",
      type: "warning",
    });
    return;
  }

  try {
    // 设置删除状态为正在进行
    isDeleting.value = true;

    await ElMessageBox.confirm(
      `确认删除所选中的【${storedIds.length}】个文件吗？删除后将无法恢复！`,
      "删除确认",
      {
        type: "warning",
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        beforeClose: async (action, instance, done) => {
          if (action === "confirm") {
            instance.confirmButtonLoading = true;
            try {
              await deleteMore({ ids: storedIds });
              clearAllSelection();
              done();
            } catch (error) {
              instance.confirmButtonLoading = false;
            }
          } else {
            done();
          }
        },
      }
    );
    ElMessage.success("删除成功");
    await search();
  } catch (error) {
    if (error !== "cancel") {
      ElMessage.error(`删除失败: ${error.message || "未知错误"}`);
      console.error("删除失败:", error);
    }
  } finally {
    // 无论成功还是失败，都要重置删除状态
    isDeleting.value = false;
  }
};

const delItem = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确认删除【${row.fileName}】吗？删除后将无法恢复！`,
      "删除确认",
      {
        type: "warning",
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        beforeClose: async (action, instance, done) => {
          if (action === "confirm") {
            instance.confirmButtonLoading = true;
            try {
              await deleteMedia({ id: row.id });
              done();
            } catch (error) {
              instance.confirmButtonLoading = false;
            }
          } else {
            done();
          }
        },
      }
    );
    ElMessage.success("删除成功");
    await search();
  } catch (error) {
    if (error !== "cancel") {
      ElMessage.error(`删除失败: ${error.message || "未知错误"}`);
      console.error("删除失败:", error);
    }
  }
};

// const dialogVisible = ref();
// const addItem = () => {
//   dialogVisible.value.addDialog();
// };

const handleClick = (row) => {
  // fileType 1文件夹 2文件
  if (row.fileType === 1) {
    router.push({
      name: "MediaDataDetail",
      query: {
        name: row.fileName,
        deviceId: router.currentRoute.value.query.deviceId,
        deviceType: router.currentRoute.value.query.deviceType,
        parentId: row.id,
      },
    });
  } else {
    // 合并图片和视频
    router.push({
      name: "VideoDetail",
      query: {
        deviceId: router.currentRoute.value.query.deviceId,
        id: row.id,
        parentId: row.parentId,
        deviceType: 2,
      },
    });
    // // 图片
    // if (row.fileType === 2 && row.suffix === "jpeg") {
    //   router.push({
    //     name: "ImgDetail",
    //     query: {
    //       deviceId: router.currentRoute.value.query.deviceId,
    //       // router.currentRoute.value.query.deviceId,
    //       id: row.id,
    //       parentId: row.parentId,
    //       deviceType: 2,
    //     },
    //   });
    // }
    // // 视频
    // if (row.fileType === 2 && row.suffix === "mp4") {
    //   router.push({
    //     name: "VideoDetail",
    //     query: {
    //       deviceId: router.currentRoute.value.query.deviceId,
    //       id: row.id,
    //       parentId: row.parentId,
    //       deviceType: 2,
    //     },
    //   });
    // }
    // // 音频
    // if (row.fileType === 2 && row.suffix === "wav") {
    //   router.push({
    //     name: "AudioDetail",
    //     query: {
    //       id: row.id,
    //     },
    //   });
    // }
  }
};

onMounted(() => {
  // 初始化当前设备ID
  currentDeviceId.value = router.currentRoute.value.query.deviceId || "";

  search();
  // initChart();

  // 初始化选中项计数
  const storedIds = getSelectedIdsFromStorage();
  selectedCount.value = storedIds.length;
});

// 添加拖拽相关的响应式变量
const dragItem = ref(null);
const dropTarget = ref(null);

// 判断是否可以拖拽到目标行
const canDrop = (targetRow) => {
  return targetRow.type === "文件夹";
};

// 拖拽开始事件
const handleDragStart = (row, event) => {
  dragItem.value = row;
  event.dataTransfer.effectAllowed = "move";
};

// 拖拽进入事件
const handleDragEnter = (row, event) => {
  if (canDrop(row) && dragItem.value !== row) {
    dropTarget.value = row;
    event.preventDefault();
  }
};

// 拖拽过程事件
const handleDragOver = (row, event) => {
  if (canDrop(row) && dragItem.value !== row) {
    event.preventDefault();
    event.dataTransfer.dropEffect = "move";
  }
};

// 拖拽离开事件
const handleDragLeave = (row, event) => {
  if (dropTarget.value === row) {
    dropTarget.value = null;
  }
};

// 放置事件
const handleDrop = (targetRow, event) => {
  event.preventDefault();

  if (
    dragItem.value &&
    targetRow &&
    canDrop(targetRow) &&
    dragItem.value !== targetRow
  ) {
    ElMessage.success(
      `成功将 "${dragItem.value.name}" 拖拽到 "${targetRow.name}"`
    );
    // 这里可以添加实际的移动文件逻辑
    console.log(`移动文件 ${dragItem.value.id} 到文件夹 ${targetRow.id}`);
  }

  dragItem.value = null;
  dropTarget.value = null;
};

// 拖拽结束事件
const handleDragEnd = () => {
  dragItem.value = null;
  dropTarget.value = null;
};
</script>

<template>
  <div class="detailPage mg-10 pd-20">
    <div class="backBtn">
      <Back width="18px" hight="18px" />
      <ElButton class="btn" @click="handleBack()">返回</ElButton>
    </div>
    <ElTabs v-model="activeName">
      <ElTabPane :label="title" name="first">
        <div class="top-list">
          <!-- <div class="top">
            <h3 class="top-title">媒体数据</h3>
            <div class="data">
              <div class="left">
                <ElProgress
                  type="dashboard"
                  :percentage="80"
                  :stroke-width="10"
                  color="#2F69EB"
                  :width="90"
                  :height="90"
                  class="progress"
                >
                  <template #default="{ percentage }">
                    <div class="percentage-flex">
                      <span class="percentage-value">{{ percentage }}%</span>
                      <span class="percentage-label">使用率</span>
                    </div>
                  </template>
                </ElProgress>
              </div>
              <div class="right">
                <div class="space-info">
                  <div class="used-space">
                    <span class="number">15MB</span>
                    <span class="label">已占资源</span>
                  </div>
                  <div class="total-space">
                    <span class="number">200MB</span>
                    <span class="label">总资源</span>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div class="top">
            <h3 class="top-title">设备名称</h3>
            <div class="data">
              <div class="left">
                <ElProgress
                  type="dashboard"
                  :percentage="80"
                  :stroke-width="10"
                  color="#67C23A"
                  :width="90"
                  :height="90"
                  class="progress2"
                >
                  <template #default="{ percentage }">
                    <div class="percentage-flex">
                      <span class="percentage-value">{{ percentage }}%</span>
                      <span class="percentage-label">使用率</span>
                    </div>
                  </template>
                </ElProgress>
              </div>
              <div class="right">
                <div class="space-info">
                  <div class="used-space">
                    <span class="number">15MB</span>
                    <span class="label">已占资源</span>
                  </div>
                  <div class="total-space">
                    <span class="number">200MB</span>
                    <span class="label">总资源</span>
                  </div>
                </div>
              </div>
            </div>
          </div> -->
          <div class="top">
            <EchartsUI ref="chartRef" style="width: 300px; height: 140px" />
          </div>
        </div>
        <div class="search">
          <ElRow>
            <ElCol :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
              <div class="searchForm">
                <div>
                  <span>名称：</span>
                  <ElInput
                    v-model="name"
                    style="width: 240px; margin-right: 16px"
                    placeholder="请输入"
                    clearable
                    @input="spaceInput"
                  />
                </div>
                <div class="searchBtn">
                  <ElButton
                    type="primary"
                    style="margin-left: 10px"
                    @click="debouncedSearch"
                    >查询</ElButton
                  >
                  <ElButton @click="resetForm()">重置</ElButton>
                </div>
              </div>
            </ElCol>
          </ElRow>
          <ElRow>
            <ElCol :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
              <div class="btns">
                <div>
                  <!-- <ElButton
                    :type="batchButtonState.type"
                    :disabled="batchButtonState.disabled"
                    style="margin-right: 10px; color: #fff !important"
                    @click="moreShare()"
                  >
                    批量分享
                  </ElButton> -->
                  <ElButton
                    :type="batchButtonState.type"
                    :disabled="batchButtonState.disabled"
                    style="margin-right: 10px; color: #fff !important"
                    @click="moreDownload()"
                  >
                    批量下载
                  </ElButton>
                  <ElButton
                    :type="batchButtonState.type"
                    :disabled="batchButtonState.disabled"
                    style="color: #fff !important"
                    @click="moreDelete()"
                  >
                    批量删除
                  </ElButton>
                </div>
                <div class="total">
                  <!-- <span>图像：14MB</span>
                  <span>视频：14MB</span>
                  <span>音频：14MB</span> -->
                </div>
              </div>
            </ElCol>
          </ElRow>
        </div>
        <ElTable
          ref="multipleTableRef"
          :data="tableData"
          stripe
          style="width: 100%"
          row-key="id"
          @selection-change="handleSelectionChange"
        >
          <ElTable.TableColumn type="selection" width="55" />
          <ElTable.TableColumn
            prop="id"
            label="id"
            align="center"
            width="100"
          />
          <!-- show-overflow-tooltip
            class-name="filename-column" -->
          <ElTable.TableColumn
            prop="fileName"
            label="名称"
            align="left"
            width="400"
          >
            <template #default="scope">
              <!-- <div
                    class="imageList"
                    :draggable="scope.row.fileType !== '1'"
                    @dragstart="handleDragStart(scope.row, $event)"
                    @dragenter="handleDragEnter(scope.row, $event)"
                    @dragover="handleDragOver(scope.row, $event)"
                    @dragleave="handleDragLeave(scope.row, $event)"
                    @drop="handleDrop(scope.row, $event)"
                    @dragend="handleDragEnd"
                    :class="{
                      'drop-target':
                        dropTarget && dropTarget.id === scope.row.id,
                    }"
                  > -->
              <div class="flex" @click="handleClick(scope.row)">
                <video
                  v-if="scope.row.suffix == 'mp4'"
                  class="video"
                  :src="scope.row.fileUrl"
                ></video>
                <ElPopover
                  placement="right"
                  :width="190"
                  :height="190"
                  trigger="hover"
                  v-if="scope.row.suffix == 'jpeg'"
                >
                  <template #reference>
                    <img
                      :src="scope.row.fileUrl"
                      crossorigin="anonymous"
                      alt=""
                      width="50px"
                    />
                  </template>
                  <template #default>
                    <img
                      :src="scope.row.fileUrl"
                      crossorigin="anonymous"
                      alt=""
                      width="190px"
                    />
                  </template>
                </ElPopover>
                <img
                  v-if="scope.row.fileType == '1'"
                  :src="defaultUrl"
                  alt=""
                  width="50px"
                />
                <!-- <ElTooltip :content="scope.row.fileName" placement="top" popper-class="multi-line-tooltip">
                  <span class="spanText">{{ scope.row.fileName }}</span>
                </ElTooltip> -->
                <!-- 使用 ElPopover 实现多行显示 -->
                <ElPopover
                  placement="top"
                  trigger="hover"
                  :width="300"
                  v-if="scope.row.fileName.length > 30"
                >
                  <template #reference>
                    <span class="spanText">{{ scope.row.fileName }}</span>
                  </template>
                  <div class="multi-line-content">
                    {{ scope.row.fileName }}
                  </div>
                </ElPopover>
                <!-- 如果文件名较短，直接显示 -->
                <span class="spanText" v-else>{{ scope.row.fileName }}</span>
              </div>
            </template>
          </ElTable.TableColumn>
          <ElTable.TableColumn prop="createTime" label="日期" align="center" />
          <ElTable.TableColumn prop="suffix" label="类型" align="center" />
          <ElTable.TableColumn prop="fileSize" label="大小" align="center" />
          <ElTable.TableColumn
            fixed="right"
            label="操作"
            align="center"
            width="150"
          >
            <template #default="scope">
              <!-- <el-button
                link
                type="primary"
                size="small"
                @click="shareItem(scope.row)"
              >
                分享
              </el-button> -->
              <el-button
                link
                type="primary"
                size="small"
                @click="downloadItem(scope.row)"
              >
                下载
              </el-button>
              <el-button
                link
                type="primary"
                size="small"
                @click="delItem(scope.row)"
              >
                删除
              </el-button>
            </template>
          </ElTable.TableColumn>
        </ElTable>
        <div class="pagination">
          <ElPagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50, 80, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </ElTabPane>
    </ElTabs>
    <share ref="shareModal" />
  </div>
</template>
<style lang="css" scoped>
.top-list {
  display: flex;
  align-items: flex-start;
  justify-content: flex-start;
  width: 100%;
  height: 140px;
  margin-bottom: 16px;
  /* 隐藏数据统计 */
  display: none;
}

.top {
  width: 300px;
  height: 140px;
  margin-bottom: 8px;
  /* padding-top: 12px;
  padding-left: 12px; */
  margin-right: 8px;
  /* border: 1px solid #dcdfe6; */
}

.top-title {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
  margin-bottom: 12px;
}

.data {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
}

.left {
  width: 90px;
  height: 90px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.percentage-flex {
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
}

.percentage-value {
  font-weight: 900;
  font-size: 20px;
  color: #303133;
  margin-bottom: 4px;
}

.percentage-label {
  font-size: 14px;
  color: #303133;
}

:deep(.el-progress-circle__track) {
  stroke: #cde8ff !important;
}

:deep(.progress2 .el-progress-circle__track) {
  stroke: #e0f3d7 !important;
}

.right {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 121px;
  height: auto;
  position: relative;
  margin-right: 22px;
}

.space-info {
  display: flex;
  justify-content: space-between;
  align-content: center;
  width: 121px;
  height: auto;
}

.used-space,
.total-space {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.space-info::after {
  content: "";
  height: 100%;
  position: absolute;
  left: 50%;
  width: 1px;
  transform: translateX(-50%);
  background: #f2f3f7;
}

.total-space {
  margin-left: 12px;
}

.number {
  font-size: 14px;
  font-weight: 500;
  color: #303133;
  margin-bottom: 2px;
}

.label {
  font-size: 12px;
  color: #909399;
}

.flex {
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
}

.btns {
  margin-top: 20px;
  margin-bottom: 12px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.total {
  font-weight: 400;
  font-size: 12px;
  color: #606266;
}

.total span {
  margin-right: 10px;
}

.total span:last-child {
  margin-right: 0px;
}

.imageList {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  cursor: pointer;
}

.spanText {
  margin-left: 4px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  width: 100%;
}

.el-table--fit {
  /* height: calc(100vh - 500px); */
  height: calc(100vh - 350px);
}

:deep(.el-table--fit .el-table__inner-wrapper:before) {
  width: 0 !important;
}

.pagination {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  width: 100%;
  padding: 20px 24px 0px 16px;
}

:deep(.el-table th) {
  background: #f5f7fa !important;
}

.searchForm {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  font-size: 14px;
}

.el-row {
  display: flex;
  place-content: center center;
}

/* @media (max-width: 950px) {
  .searchForm {
    flex-direction: column;
    align-items: flex-start;
  }

  .searchBtn {
    margin-top: 10px;
  }
} */

:deep(.el-image__preview) {
  width: 50px !important;
}

video {
  height: 50px;
  width: 50px;
}

/* 添加拖拽相关样式 */
.imageList {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  cursor: pointer;
  padding: 5px;
  border-radius: 4px;
  transition: all 0.2s ease;
}

.imageList:hover {
  background-color: #f5f7fa;
}

.imageList[draggable="true"] {
  cursor: move;
}

.imageList.drop-target {
  background-color: #e6f7ff;
  border: 1px dashed #409eff;
}

.imageList.drop-target .spanText {
  color: #409eff;
  font-weight: bold;
}

/* 禁止文件夹行的拖拽样式 */
.imageList[draggable="false"] {
  cursor: default;
}

:deep(.filename-column .cell) {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

:deep(.el-tooltip) {
  max-width: 300px !important;
}

:deep(.filename-column .el-tooltip) {
  max-width: 280px !important;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 添加多行内容样式 */
.multi-line-content {
  white-space: pre-wrap;
  word-break: break-all;
  line-height: 1.5;
  max-height: 200px;
  overflow-y: auto;
}

.spanText {
  margin-left: 4px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  width: 100%;
}
</style>
